/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.meta.controller.develop;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.JSONReader;
import com.je.common.base.DynaBean;
import com.je.common.base.mvc.AbstractPlatformController;
import com.je.common.base.mvc.BaseMethodArgument;
import com.je.common.base.result.BaseRespResult;
import com.je.common.base.service.rpc.BeanService;
import com.je.common.base.service.rpc.SystemSettingRpcService;
import com.je.common.base.util.StringUtil;
import com.je.ibatis.extension.conditions.ConditionsWrapper;
import com.je.ibatis.extension.plugins.pagination.Page;
import com.je.meta.service.develop.DevelopService;
import com.je.rbac.rpc.AccountRpcService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping(value = "/je/meta/develop")
public class DevelopController extends AbstractPlatformController {

    @Autowired
    private DevelopService developService;
    @Autowired
    private SystemSettingRpcService systemSettingRpcService;
    @Autowired
    private AccountRpcService accountRpcService;


    /**
     * 获取核心资源的总数
     */
    @RequestMapping(value = "/getCoreResourceCount", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ResponseBody
    public BaseRespResult getCoreResourceCount(BaseMethodArgument param, HttpServletRequest request) {
        DynaBean dynaBean = developService.getCoreResourceCount();
        return BaseRespResult.successResult(dynaBean);
    }

    /**
     * 从平台设置里获取开发团队成员信息
     */
    /**
     * 获取核心资源的总数
     */
    @RequestMapping(value = "/getDevelopUser", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ResponseBody
    public BaseRespResult getDevelopUser(BaseMethodArgument param, HttpServletRequest request) {
        String accountIds = systemSettingRpcService.findSettingValue("JE_SYS_ADMIN");
        List<DynaBean> accountList = accountRpcService.findBatchAccount("JE_RBAC_VACCOUNTDEPT", accountIds, "JE_RBAC_ACCOUNTDEPT_ID");
        Map<String, Object> accountMap = accountList.stream().collect(Collectors.toMap(p -> String.valueOf(p.get("JE_RBAC_ACCOUNTDEPT_ID")), p -> p));
        List<Map<String, String>> list = new ArrayList<>();
        if (StringUtil.isNotEmpty(accountIds)) {
            String[] accountIdArr = accountIds.split(",");
            for (int i = 0; i < accountIdArr.length; i++) {
                Map<String, String> map = new HashMap<>();
                if (accountMap.containsKey(accountIdArr[i])) {
                    DynaBean accountDynaBean = (DynaBean) accountMap.get(accountIdArr[i]);
                    map.put("accountId", accountDynaBean.getStr("JE_RBAC_ACCOUNT_ID"));
                    map.put("fileKey", getFileKeyFromJson(accountDynaBean.get("ACCOUNT_AVATAR") == null ? "" : accountDynaBean.get("ACCOUNT_AVATAR").toString()));
                    map.put("accountName", accountDynaBean.getStr("ACCOUNT_NAME"));
                }
                list.add(map);
            }
        }
        return BaseRespResult.successResult(list);
    }

    private String getFileKeyFromJson(String json) {
        if (StringUtil.isNotEmpty(json)) {
            JSON.config(JSONReader.Feature.AllowUnQuotedFieldNames);
            Object object = JSON.parse(json);
            JSONObject jsonObject = new JSONObject();
            if (object instanceof JSONArray) {
                JSONArray jsonArray = (JSONArray) object;
                if (jsonArray != null && jsonArray.size() > 0) {
                    jsonObject = jsonArray.getJSONObject(0);
                }
            }
            if (object instanceof JSONObject) {
                jsonObject = (JSONObject) object;
            }
            if (jsonObject.containsKey("fileKey")) {
                return jsonObject.getString("fileKey");
            }
        }
        return null;
    }

    @RequestMapping(value = "/loadsvc", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    public BaseRespResult loadsvc(HttpServletRequest request) {
        String code = request.getParameter("code");
        String dev = request.getParameter("dev");
        if (StringUtil.isEmpty(code)) {
            return BaseRespResult.errorResult("请设置编码！");
        }
        if (StringUtil.isEmpty(dev)) {
            return BaseRespResult.errorResult("请设置开发");
        }
        Map<String, Object> params = new HashMap<>();
        params.put("code", code);
        params.put("dev", dev);
        String message = "";
        Map<String, Object> result = new HashMap<>();

        try {
            message = HttpUtil.post("https://jesvc.com/je/jesvc/server/info", params, 1000 * 10);
        } catch (Exception e) {
            return BaseRespResult.successResult(result);
        }

        try {
            JSONObject messageObj = JSON.parseObject(message);
            if (!messageObj.getBoolean("success")) {
                return BaseRespResult.errorResult(messageObj.getString("message"));
            }
            messageObj.getJSONObject("data").forEach((k, v) -> {
                result.put(k, v);
            });
        } catch (Throwable e) {
            return BaseRespResult.errorResult(e.getMessage());
        }
        return BaseRespResult.successResult(result);
    }

    /**
     * 获取操作日志
     *
     * @param param 前端数据
     */
    @RequestMapping(value = "/loadDevelopUserLog", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ResponseBody
    public BaseRespResult loadDevelopUserLog(BaseMethodArgument param, HttpServletRequest request) {
        String tableCode = param.getTableCode();
        DynaBean dynaBean = (DynaBean) request.getAttribute("dynaBean");
        if (StringUtil.isEmpty(tableCode)) {
            tableCode = "JE_CORE_DEVELOPLOG";
            param.setTableCode(tableCode);
            dynaBean.set(BeanService.KEY_TABLE_CODE, tableCode);
        }
        String accountId = getStringParameter(request, "accountId");
        String whereSql = param.getWhereSql();
        if (StringUtil.isNotEmpty(accountId)) {
            whereSql += " AND DEVELOPLOG_USERID='" + accountId + "'";
        } else {
            whereSql = " ";
        }
        String orderSql = param.getOrderSql();
        if (StringUtil.isEmpty(orderSql)) {
            orderSql = " ORDER BY SY_CREATETIME DESC";
        }
        dynaBean.set(BeanService.KEY_WHERE, whereSql);
        dynaBean.set(BeanService.KEY_ORDER, orderSql);
        param.setOrderSql(orderSql);
        param.setWhereSql(whereSql);
        Page page = new Page(param.getStart(), param.getLimit());
        List<DynaBean> list = metaService.select(dynaBean.getStr(BeanService.KEY_TABLE_CODE), page, ConditionsWrapper.builder().apply(dynaBean.getStr(BeanService.KEY_WHERE) + " " + dynaBean.getStr(BeanService.KEY_ORDER)));
        String accountIds = "";
        for (DynaBean logDynaBean : list) {
            if (StringUtil.isNotEmpty(accountIds)) {
                accountIds = accountIds + "," + logDynaBean.getStr("DEVELOPLOG_USERID");
            } else {
                accountIds = logDynaBean.getStr("DEVELOPLOG_USERID");
            }
        }
        List<DynaBean> accountList = accountRpcService.findBatchAccount("JE_RBAC_ACCOUNT", accountIds, "JE_RBAC_ACCOUNT_ID");
        Map<String, Object> accountMap = accountList.stream().collect(Collectors.toMap(p -> String.valueOf(p.get("JE_RBAC_ACCOUNT_ID")), p -> String.valueOf(p.get("ACCOUNT_AVATAR"))));
        for (DynaBean logDynaBean : list) {
            if (accountMap.containsKey(logDynaBean.getStr("DEVELOPLOG_USERID"))) {
                logDynaBean.setStr("fileKey", getFileKeyFromJson(accountMap.get(logDynaBean.getStr("DEVELOPLOG_USERID")) == null ? "" : accountMap.get(logDynaBean.getStr("DEVELOPLOG_USERID")).toString()));
            } else {
                logDynaBean.setStr("fileKey", "");
            }
        }
        return BaseRespResult.successResultPage(list, Long.valueOf(page.getTotal()));
    }


}
